# import pymysql
import json
from myapp.utils.connection import POOL

# conn = pymysql.Connect(host='localhost', user='root',
#                        passwd='123456', db='zhifou', port=3306, charset='utf8')
kw = '企业复工'  # 测试用
pidList = []


def detail_loadjson(key, mid=''):
    conn = POOL.connection()
    cur = conn.cursor()
    print(key)
    sql = ''
    if mid == '':
        sql = "SELECT mid,userid,text,created_at,reposts_count,comments_count,attitudes_count,followers_count,follow_count" \
            " FROM {}_findson WHERE pid = 0 ORDER BY (reposts_count+attitudes_count) DESC LIMIT 10".format(
                key)
    else:
        sql = "SELECT mid,userid,text,created_at,reposts_count,comments_count,attitudes_count,followers_count,follow_count" \
            " FROM {}_findson WHERE mid = {}".format(
                key, mid)
    cur.execute(sql)
    datatuple = cur.fetchall()
    print(datatuple)

    json_file = []

    for data in datatuple:
        set = {}
        set['weiBoId'] = data[0]
        set['userId'] = data[1]
        set['imgUrl'] = ""
        set['content'] = data[2]
        set['timeData'] = data[3].strftime("%Y-%m-%d %H:%M:%S")
        set['transferData'] = data[4]
        set['commentData'] = data[5]
        set['goodData'] = data[6]
        set['followerData'] = data[7]
        set['followData'] = data[8]
        set['linkUrl'] = 'https://m.weibo.cn/detail/{}'.format(data[0])
        json_file.append(set)

    cur.close()

    conn.close()
    return {"data": json_file}


def writefile(key):
    jsonData = detail_loadjson(key)
    jsondatar = json.dumps(jsonData, ensure_ascii=False)
    print(jsondatar)
    f = open(r'Detail.json', 'w+', encoding="utf8")
    # 写数据
    f.write(jsondatar)
    # 关闭文件
    f.close()


if __name__ == '__main__':
    writefile(kw)
